<template>
  <div class="app-container">
    <div class="top">
      <span class="title">{{ title }}</span>
    </div>

    <van-form ref="form">
      <van-cell-group>
        <item v-for="item in formList" :key="item.id" :node="item"> </item>
      </van-cell-group>
    </van-form>

    <van-button
      v-if="formList.length"
      style="margin: 10px 5%; width: 90%"
      round
      type="info"
      @click="submit()"
      >提交</van-button
    >
  </div>
</template>

<script>
import { getSurveyById } from "@/api/work";
import { submitSurvey, updateSurveySubmit } from "@/api/mobile";
import { debounce, Base64toFile } from "@/utils/index";
import { uploadImage } from "@/api/form";
import item from "./item.vue";
import { Notify } from "vant";
export default {
  components: { item, [Notify.Component.name]: Notify.Component },
  data() {
    return {
      formList: [],
      logicList: [],
      id: null,
      debounceInit: null,
      title: null,
      bak: null,
    };
  },

  created() {
    this.$route.query.id
      ? (this.id = this.$route.query.id)
      : this.$router.push({ name: "Dashboard" });

    this.debounceInit = debounce(100, this.check);
    getSurveyById(this.id).then((res) => {
      let formList = JSON.parse(res.text);
      let logicList = JSON.parse(res.logic);
      formList.map((i) => (i.show = true));

      this.check([logicList, formList]);

      this.formList = formList;
      this.logicList = logicList;

      this.bak = JSON.parse(res.text);
      this.title = res.title;
    });
  },

  mounted() {
    this.form = this.$refs.form;
  },

  methods: {
    submit() {
      let a = 0;
      this.formList.map((i) => {
        i.type == 9 &&
        i.answer.indexOf("http://") == -1 &&
        i.answer.indexOf("https://") == -1
          ? (a += 1)
          : null;
      });
      this.$refs.form
        .validate()
        .then((res) => {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          if (a == 0) {
            submitSurvey(this.id, {
              text: JSON.stringify(this.formList),
            })
              .then((res) => {
                this.$toast({
                  message: "提交成功",
                  icon: "passed",
                });
                this.next();
              })
              .catch((res) => {
                this.$toast({
                  message: res.response.data.message,
                  icon: "passed",
                });
              })
              .finally((res) => {
                loading.close();
              });
            return;
          }
          try {
            //保证loading可以关闭
            for (let i = 0; i < this.formList.length; i++) {
              if (this.formList[i].type == 9) {
                let spark = new SparkMD5.ArrayBuffer();
                let fileReader = new FileReader();
                let file = Base64toFile(this.formList[i].answer);
                fileReader.readAsArrayBuffer(file.slice(0, file.size));
                fileReader.onload = (e) => {
                  spark.append(e.target.result);
                  let md5 = spark.end();
                  let form = new FormData();
                  form.set("file", file);
                  form.set("md5", md5);
                  uploadImage(form).then((e) => {
                    a = a - 1;
                    this.formList[i].answer = e.file;
                    if (a == 0) {
                      submitSurvey(this.id, {
                        text: JSON.stringify(this.formList),
                      })
                        .then((res) => {
                          Notify({ message: "提交成功", type: "success" });
                          this.next();
                        })
                        .finally((res) => {
                          loading.close();
                        });
                    }
                  });
                };
              }
            }
          } catch (error) {
            loading.close();
          }
        })
        .catch((res) => {
          console.log(res);
        });
    },

    check(e) {
      let logicList = e[0];
      let formList = e[1];
      for (let j = 0; j < logicList.length; j++) {
        const l = logicList[j];
        let t = 0;
        for (let i = 0; i < l.list.length; i++) {
          const a = l.list[i];
          let target = formList[formList.map((item) => item.id).indexOf(a.id)];
          if (a.type == 0) {
            if (target.answer == a.answer) t++;
          } else {
            if (target.answer != a.answer) t++;
          }
        }
        let index = formList.map((item) => item.id).indexOf(parseInt(l.id));
        if (l.type == 0) {
          t >= l.list.length
            ? formList[index].show == true
              ? null
              : this.$set(formList[index], "show", true)
            : formList[index].show == false
            ? null
            : this.$set(formList[index], "show", false);
        } else {
          t > 0
            ? formList[index].show == true
              ? null
              : this.$set(formList[index], "show", true)
            : formList[index].show == false
            ? null
            : this.$set(formList[index], "show", false);
        }
      }
    },

    //重置表单
    resetForm() {
      for (let i = 0; i < this.bak.length; i++) {
        this.formList[i].answer = this.bak[i].answer;
      }
    },

    //执行完提交后执行
    next() {},
  },

  watch: {
    formList: {
      handler(n, o) {
        this.debounceInit
          ? this.debounceInit(this.logicList, this.formList)
          : null;
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 0px;
  background: white;
}
.app-container >>> .el-scrollbar__wrap {
  height: 100%;
  width: 100%;
  overflow-x: hidden;
}
.app-container >>> .el-scrollbar__wrap::-webkit-scrollbar {
  display: none;
}
.app-container >>> .el-scrollbar__view {
  height: 100%;
}
.top {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  flex-direction: column;
  align-items: center;
  background: white;
}
.title {
  font-size: 20px;
  color: #303133;
}
</style>
